#include "speech.h"

speech::speech(QObject *parent) : QObject(parent)
{

}
QString speech::speechIdentify(QString fileName)
{
    //获取access_token
    QString tokenUrl = QString(baiduTokenUrl).arg(client_id).arg(client_secret);
    http my_http;
    QMap<QString,QString> header;
    header.insert(QString("Content-Type"),QString("audio/pcm;rate=16000"));
    QByteArray requestData;
    QByteArray replyData;
    QString accesstoken;
    bool result = my_http.post_sync(tokenUrl,header,requestData,replyData);
    if(result)
    {
       QString key = "access_token";
       accesstoken = getJsonValue(replyData,key);
      // qDebug() << accesstoken;
    }
    else
    {
       return "";
    }
    //语音识别
    QString speechurl = QString(baiduSpeechUrl.arg(QHostInfo::localHostName()).arg(accesstoken));

    //把文件转换为QbyteArrey
    QFile file;
    file.setFileName(fileName);
    file.open(QIODevice::ReadOnly);
    requestData = file.readAll();
    file.close();

    replyData.clear();
    //再次发起请求
       result = my_http.post_sync(speechurl,header,requestData,replyData);
      // qDebug()<<result;
    if(result)
    {
        QString key = "result";
        QString text = getJsonValue(replyData,key);
        qDebug()<<text;
        //qDebug()<<replyData;
        return text;
    }
    else
    {
        QMessageBox::warning(NULL,"识别提示","识别失败");
    }

    return "";
}
QString speech::getJsonValue(QByteArray ba, QString key)
{
    QJsonParseError parseerror;
    QJsonDocument jsondocument = QJsonDocument::fromJson(ba,&parseerror);
    if(parseerror.error == QJsonParseError::NoError)
    {
        if(jsondocument.isObject())
        {
            QJsonObject jsonobj = jsondocument.object();
            if(jsonobj.contains(key))
            {
                    QJsonValue jsonval = jsonobj.value(key);
                    if(jsonval.isString())
                    {
                        return jsonval.toString();
                    }
                    else if(jsonval.isArray())
                    {
                        QJsonArray arr = jsonval.toArray();//转换为jsonArrey
                        QJsonValue jv = arr.at(0);
                        return jv.toString();
                    }
            }
        }
    }
    return "...";
}
